package com.ruanyun.system;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruanyun.base.BaseJunit;
import com.ruanyun.sys.modular.system.entity.SysDistrict;
import com.ruanyun.sys.modular.system.mapper.SysDistrictMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class HttpUtils extends BaseJunit {

    @Autowired
    private SysDistrictMapper sysDistrictMapper;

    @Test
    public void test() {
        //高德的key 申请时选择web服务
        String gaodeKey = "";

        //
        sysDistrictMapper.delete(null); //删除所有的数据
        //一个http请求  这个方法放在羡慕
        String res =
                HttpUtils.sendPost("http://restapi.amap.com/v3/config/district", "key=" + gaodeKey + "&subdistrict=4");
        JSONObject json = JSONObject.parseObject(res);
        int count = 0;
        if (json.get("status").equals("1")) {
            //国家 暂时只有中国
            JSONArray districts = json.getJSONArray("districts");

            for (int i = 0; i < districts.size(); i++) {
                JSONObject district = districts.getJSONObject(i);
                Long parentId = this.saveDistrict(null, district.getString("name"), district.getString("adcode"), district.getString("level"));
                //省份
                JSONArray provinces = district.getJSONArray("districts");
                for (int j = 0; j < provinces.size(); j++) {
                    JSONObject province = provinces.getJSONObject(j);
                    Long provinceParentId = this.saveDistrict(parentId, province.getString("name"), province.getString("adcode"), province.getString("level"));

                    System.out.println(
                            "province ::::::  ====  name:" + province.getString("name") +
                                    "   center:" + province.getString("center") +
                                    "   adcode:" + province.getString("adcode")
                    );
                    //在这里新增省份 到表中
                    //市
                    JSONArray citys = province.getJSONArray("districts");
                    for (int k = 0; k < citys.size(); k++) {
                        JSONObject city = citys.getJSONObject(k);
                        Long cityParentId = this.saveDistrict(provinceParentId, city.getString("name"), city.getString("adcode"), city.getString("level"));

                        System.out.println(
                                "city ::::::  ====  name:" + city.getString("name") +
                                        "   center:" + city.getString("center") +
                                        "   adcode:" + city.getString("adcode")
                        );

                        //在这里新增市 到表中
                        //区
                        JSONArray areas = city.getJSONArray("districts");
                        for (int l = 0; l < areas.size(); l++) {
                            JSONObject area = areas.getJSONObject(l);
                            Long areaParentId = this.saveDistrict(cityParentId, area.getString("name"), area.getString("adcode"), area.getString("level"));
                            System.out.println(
                                    "area ::::::  ====  name:" + area.getString("name") +
                                            "   center:" + area.getString("center") +
                                            "   adcode:" + area.getString("adcode")
                            );
                            //在这里新增区 到表中
                            // 街道
                            JSONArray streets = city.getJSONArray("districts");//
                            for (int m = 0; m < streets.size(); m++) {
                                JSONObject street = areas.getJSONObject(m);
                                this.saveDistrict(areaParentId, street.getString("name"), street.getString("adcode"), street.getString("level"));
                                count++;
                                System.out.println(
                                        "area ::::::  ====  name:" + area.getString("name") +
                                                "   center:" + area.getString("center") +
                                                "   adcode:" + area.getString("adcode")
                                );
                                //在这里新增区 到表中

                            }

                        }
                    }
                }
            }
            System.out.println("获取成功 共" + count + "条数据");
        } else {
            System.err.println(json.get("info"));
        }
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            String urlNameString = url + "?" + param;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e.getMessage());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
            }
        }
        return result.toString();
    }

    private Long saveDistrict(Long parentId, String districtName, String districtCode, String level) {
        SysDistrict district = new SysDistrict();
        district.setParentId(parentId);
        district.setDistrictName(districtName);
        district.setDistrictCode(districtCode);
        int districtLevel = 0;
        if (StrUtil.equals(level, "country")) {
            districtLevel = 0;
        } else if (StrUtil.equals(level, "province")) {
            districtLevel = 1;
        } else if (StrUtil.equals(level, "city")) {
            districtLevel = 2;
        } else if (StrUtil.equals(level, "district")) {
            districtLevel = 3;
        } else {
            districtLevel = 4;
        }
        district.setDistrictLevel(districtLevel);
        district.setDelete(false);
        this.sysDistrictMapper.insert(district);
        return district.getDistrictId();
    }
}
